package com.sctvcloud.renhe.ui.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.flyco.tablayout.SlidingTabLayoutWithIcon;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.utils.DateUtils;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.ServerTime;
import com.ruihang.generalibrary.utils.UrlUtils;
import com.sctvcloud.renhe.R;
import com.sctvcloud.renhe.base.BaseFragment;
import com.sctvcloud.renhe.application.Constances;
import com.sctvcloud.renhe.beans.FChannel;
import com.sctvcloud.renhe.beans.FLiveProgram;
import com.sctvcloud.renhe.beans.FProgram;
import com.sctvcloud.renhe.beans.TvLivingList;
import com.sctvcloud.renhe.ui.adapter.TvAdapter;
import com.sctvcloud.renhe.ui.adapter.TvLivingAdapter;
import com.sctvcloud.renhe.ui.entity.TabLayoutEntity;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2017/7/13 0013.
 * 未使用
 */
public class TvPageFragment extends ColumnBaseFragment {
    private final int WHAT_REFRESH_TIME = 919;

    @BindView(R.id.fragment_tv_viewPager)
    protected ViewPager viewPager;
    @BindView(R.id.tab_layout)
    protected SlidingTabLayoutWithIcon tabLayout;
    private TvAdapter tvAdapter;

    private ArrayList<FChannel> channels = new ArrayList<>();

    private TvLivingAdapter livingAdapter;
    private boolean mIsLoading = false;
    private List<FProgram> currentPrograms;
    private Handler handler;
    private FChannel currentChannel;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg != null) {
                    handMsg(msg);
                }
            }
        };
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        ColumnBaseFragment cbf = getCurrentFragment();
        if (cbf != null) {
            cbf.setParentShowing(!hidden);
        }
    }

    @Override
    public boolean hasShowPlayer() {
        BaseFragment bf = getCurrentFragment();
        return bf != null && bf.hasShowPlayer();
    }

    @Override
    public boolean onBackPressed() {
        ColumnBaseFragment f = getCurrentFragment();
        if (f != null && f.onBackPressed()) {
            return true;
        }
        return super.onBackPressed();
    }

    private ColumnBaseFragment getCurrentFragment() {
        if (viewPager == null || tvAdapter == null || tvAdapter.getCount() == 0) {
            return null;
        }
        ColumnBaseFragment cbf = tvAdapter.getFragmentByPos(viewPager.getCurrentItem());
        JLog.e("ffsf " + cbf);
        return cbf;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_tv_page, container, false);
        ButterKnife.bind(this, view);
        return view;
    }


    @Override
    public void onDestroyView() {
        if (handler != null) {
            handler.removeMessages(WHAT_REFRESH_TIME);
        }
        super.onDestroyView();
    }

    ArrayList<CustomTabEntity> tableEntities;

    public void setData(List<FChannel> fChannels) {
        this.channels = (ArrayList<FChannel>) fChannels;
        tableEntities = new ArrayList<>();
        if (ListUtils.isListValued(channels)) {
            currentChannel = channels.get(0);
        }
        for (FChannel fChannel : channels) {
            CustomTabEntity entity = new TabLayoutEntity(fChannel.getChannelName(), UrlUtils.linkUrls(Constances.ST_BASE_URL, fChannel.getChannelImage()));
            tableEntities.add(entity);
        }
        if (tvAdapter != null) {
            tvAdapter.setData(channels);

        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (tabLayout != null) {
//                    tabLayout.setTabData(tableEntities);
                    tabLayout.setViewPager(viewPager, tableEntities);
                    tabLayout.notifyDataSetChanged();
                }
            }
        }, 500);

    }

    @Override
    protected void initViews(View v, @Nullable Bundle savedInstanceState) {
//        tableEntities = new ArrayList<>();
//        tabLayout.setTabData(tableEntities);
//        tabLayout.setOnTabSelectListener(new OnTabSelectListener() {
//            @Override
//            public void onTabSelect(int position) {
////                viewPager.setCurrentItem(position);
//                ((TvFragment) getParentFragment()).setPlayMedia(channels.get(position), false);
//                currentChannel = channels.get(position);
//            }
//
//            @Override
//            public void onTabReselect(int position) {
//
//            }
//        });
        tvAdapter = new TvAdapter(getChildFragmentManager(), getActivity(), channels);
//        tvAdapter.setParentShowing(isThisShowing);
        viewPager.setAdapter(tvAdapter);
//        viewPager.setOffscreenPageLimit(1);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
//                tabLayout.setCurrentTab(position);
                ((TvFragment) getParentFragment()).setPlayMedia(channels.get(position), false);
                currentChannel = channels.get(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        viewPager.setCurrentItem(0);


    }

    @Override
    protected boolean onFragmentShow(boolean isFirst, boolean isCallFromResume) {
        if (currentChannel != null) {
            ((TvFragment) getParentFragment()).setPlayMedia(currentChannel, false);
        }
        return super.onFragmentShow(isFirst, isCallFromResume);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (tvAdapter != null) {
            tvAdapter.setParentShowing(isVisibleToUser);
        }
    }


    private void handMsg(Message msg) {
        if (msg.what == WHAT_REFRESH_TIME) {
            handler.removeMessages(WHAT_REFRESH_TIME);
            refreshProgramTime();
        }
    }


    private synchronized void onNetFinish() {
        mIsLoading = false;
    }

    /**
     * 获取当天的节目单,调用前需检查非空
     *
     * @return
     */
    private List<FProgram> getCurrentDayProgramList(List<FLiveProgram> datePrograms) {
        if (!ListUtils.isListValued(datePrograms)) {
            return null;
        }
        for (int i = 0; i < datePrograms.size(); i++) {
            FLiveProgram flp = datePrograms.get(i);
            if (flp != null) {
                if (DateUtils.isCurrentDate(DateUtils.getDataDate(flp))) {
                    return flp.getProgrammeList();
                }
            }
        }
        return null;
    }

    private int getCurrentProgramPos(List<FProgram> list) {
        long currentLong = DateUtils.getHourLong(ServerTime.getInstance(0).getServerRealTimeMilByEla());
        //JLog.e("aasa  " + DateUtils.getHoursLong("00:00:00") + "   " + Long.MIN_VALUE);
        if (ListUtils.isListValued(list)) {
            for (int i = list.size() - 1; i >= 0; i--) {
                FProgram fp = list.get(i);
                if (fp == null) {
                    list.remove(i);//此处不能将i加1
                    continue;
                }
                long time = fp.getStartTimeLongTemp();
                String s = fp.getStartTime();
                if (time <= DateUtils.OUTHOUR) {//中国的时区早晨8点为0,晚上0点为-2880000
                    time = DateUtils.getHoursLong(s);
                    fp.setStartTimeLongTemp(time);
                    JLog.e("long  " + time + "   " + s);
                }
                fp.setHasOutTime(false);
                if (currentLong > time && !TextUtils.isEmpty(s)) {
                    return i;
                }
            }
        }
        return -1;
    }

    private void refreshProgramTime() {
        if (livingAdapter != null) {
            int oldPos = livingAdapter.getSelectPos();
            int pos = getCurrentProgramPos(currentPrograms);
            if (oldPos != pos) {
                livingAdapter.setSelectPos(pos);
                if (oldPos >= 0) {
                    if (pos > oldPos) {
                        currentPrograms.get(oldPos).setHasOutTime(true);
                    }
                    livingAdapter.notifyItemChanged(oldPos);
                }
                if (pos >= 0) {
                    livingAdapter.notifyItemChanged(pos);
                }
            }
            if (pos >= 0 && pos < livingAdapter.getItemCount() - 1) {
                resetRemind(currentPrograms.get(pos + 1));
            }
        }
    }

    private void resetRemind(FProgram fp) {
        long time = fp.getStartTimeLongTemp();
        long cha = time - ServerTime.getInstance(0).getServerRealTimeMilByEla();
        if (cha > 0) {
            handler.sendEmptyMessageDelayed(WHAT_REFRESH_TIME, cha);
        }
    }

    private void convertData(TvLivingList tvLivingList) {
        List<FProgram> list = new ArrayList<>();
        String dateStr = DateUtils.formatDate(new Date(System.currentTimeMillis()), "yyyy-MM-dd");

        //测试修改数据（将当前系统时间替换为接口字段时间，以便能显示数据）
//        dateStr = dateStr.replace(dateStr.substring(dateStr.lastIndexOf("-"), dateStr.length()), "-28");
        if (!ListUtils.isListValued(tvLivingList.getLiveProgrammeList())) {
            return;
        }

        for (int i = 0; i < tvLivingList.getLiveProgrammeList().size(); i++) {
            if (TextUtils.isEmpty(tvLivingList.getLiveProgrammeList().get(i).getLiveProgrammeDate())) {
                continue;
            }
            String dateS = tvLivingList.getLiveProgrammeList().get(i).getLiveProgrammeDate();
            if (!TextUtils.isEmpty(dateS) && dateS.contains(dateStr) && tvLivingList.getLiveProgrammeList().get
                    (i).getProgrammeList() != null) {
                list.addAll(tvLivingList.getLiveProgrammeList().get(i).getProgrammeList());
            }
        }

        if (list.size() == 0) {
            makeToast(R.string.no_program_data);
            return;
        }

//        initData(list);
    }


    private OnItemInternalClick livingOnItemClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
//            FProgram fProgram = livingAdapter.getItem(position);
//            ((TvFragment) getParentFragment()).setPlayMedia(fProgram);
        }
    };

    private void makeToast(int strRes) {
//        if (((TvFragment) getParentFragment()).getIndexInViewPager() != ((TvFragment) getParentFragment().getParentFragment())
//                .getCurrentSelectedIndex()) {
//            return;
//        }
        // toast(R.string.loading_no_data);
    }
}
